from __future__ import with_statement
import sys
from unittest import TestCase, main

from sqlalchemy.orm import clear_mappers
from webtest import TestApp
import simplejson

from clutch.wsgi import make_app_test as make_app
from clutch.command import ReloadCommand
from clutch.config import ConfigObj
from clutch.globals import C, G

class TestModel(TestCase):

    def setUp(self):
        self.app = make_app({}, **{
            'use':'egg:Clutch',
            'clutch.app_config':'TestApplication#main',
            'clutch.db.table_prefix':'test_',
            'clutch.api.id': { 'clutch.app_config':'Clutch#identity',
                               'clutch.db.table_prefix':'id_' }
            })
        self.tester = TestApp(self.app)
        self.tester.get('/tests/model/create_schema')

    def testCRUD(self):
        res = self.tester.post('/tests/model/data')
        self.assertEqual(res.json['item'], dict(id=None, value=None, ssn=None))
        res = self.tester.get('/tests/model/data')
        self.assertEqual(len(res.json['items']), 1)
        res = self.tester.put('/tests/model/data/1', params=dict(value='foo'))
        self.assertEqual(res.json['item']['value'], 'foo')
        res = self.tester.get('/tests/model/data')
        self.assertEqual(res.json['items'][0]['value'], 'foo')
        res = self.tester.delete('/tests/model/data/1')
        res = self.tester.get('/tests/model/data')
        self.assertEqual(len(res.json['items']), 0)

    def testMulti(self):
        res = self.tester.get('/tests/model/test_query_users')
        self.assertEqual(res.json['users'], [])
        res = self.tester.get('/tests/model/test_create_user')
        self.assertEqual(res.json['user']['email_address'], 'rick446@usa.net')
        res = self.tester.get('/tests/model/test_query_users')
        self.assertEqual(len(res.json['users']), 1)

    def testMultiError(self):
        self.tester.get('/tests/model/test_error_id', status=410)
        res = self.tester.get('/tests/model/test_query_users')
        self.assertEqual(res.json['users'], [])
        
        
        
